<template>
  <div class="rule-container">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="规则名称" prop="title">
              <el-input v-model="queryParams.ruleName" placeholder="请输入规则名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
              <el-button type="primary" icon="Plus" @click="handleAdd">新增规则</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <!-- 操作区域 -->
    <!--    <div class="action-area">-->
    <!--      <el-button type="primary" icon="Plus" @click="handleAdd">新增规则</el-button>-->
    <!--      <el-button icon="Refresh" @click="resetQuery"></el-button>-->
    <!--    </div>-->

    <!-- 规则列表 -->
    <el-card shadow="hover" class="table-card">
      <el-table v-loading="loading" :data="ruleList" border stripe>
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="规则编号" width="100" align="center">
          <template #default="{ $index }">
            {{ $index + 1 }}
          </template>
        </el-table-column>
        <el-table-column label="规则名称" prop="ruleName" :show-overflow-tooltip="true" min-width="150" />
        <el-table-column label="预警类型" prop="warningType" width="150" align="center">
          <template #default="scope">
            {{ getWarningTypeName(scope.row.warningType) }}
          </template>
        </el-table-column>
        <el-table-column label="触发条件" prop="triggerCondition" min-width="180" :show-overflow-tooltip="true" />
        <el-table-column label="预警级别" prop="warningLevel" width="100" align="center">
          <template #default="scope">
            <el-tag :type="getWarningLevelType(scope.row.warningLevel)" effect="dark">
              {{ getWarningLevelName(scope.row.warningLevel) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="通知方式" prop="notificationMethod" width="120" align="center">
          <template #default="scope">
            <el-tooltip :content="getNotificationMethodText(scope.row.notificationMethod)" placement="top">
              <div class="notification-icons">
                <template v-for="method in scope.row.notificationMethod" :key="method">
                  <el-icon v-if="method === 'email'">
                    <Message />
                  </el-icon>
                  <el-icon v-if="method === 'sms'">
                    <ChatLineRound />
                  </el-icon>
                  <el-icon v-if="method === 'system'">
                    <Bell />
                  </el-icon>
                </template>
              </div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="状态" prop="status" width="100" align="center">
          <template #default="scope">
            <el-switch v-model="scope.row.status" :active-value="0" :inactive-value="1" @change="handleStatusChange(scope.row)" />
          </template>
        </el-table-column>
        <el-table-column label="创建时间" prop="createTime" width="160" align="center">
          <template #default="scope">
            <span>{{ formatDate(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right" align="center">
          <template #default="scope">
            <el-button size="small" type="primary" link @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="small" type="success" link @click="handleTest(scope.row)">测试</el-button>
            <el-button size="small" type="danger" link @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 30, 50]"
          :background="true"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @current-change="handlePageChange"
          @size-change="handleSizeChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑规则弹窗 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="60%" destroy-on-close append-to-body>
      <el-form ref="ruleFormRef" :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="规则名称" prop="ruleName">
              <el-input v-model="form.ruleName" placeholder="请输入规则名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="预警类型" prop="warningType">
              <el-select v-model="form.warningType" placeholder="请选择预警类型" style="width: 100%">
                <el-option v-for="dict in warningTypeOptions" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="触发条件" prop="triggerCondition">
          <el-input v-model="form.triggerCondition" placeholder="请输入触发条件描述" />
        </el-form-item>

        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="预警级别" prop="warningLevel">
              <el-select v-model="form.warningLevel" placeholder="请选择预警级别" style="width: 100%">
                <el-option v-for="item in warningLevelOptions" :key="item.dictValue" :label="item.dictLabel" :value="item.dictValue" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="规则状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio :label="0">启用</el-radio>
                <el-radio :label="1">禁用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="通知方式" prop="notificationMethod">
          <el-checkbox-group v-model="form.notificationMethod">
            <el-checkbox v-for="item in notificationMethodOptions" :key="item.dictValue" :label="item.dictValue">
              {{ item.dictLabel }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>

        <el-form-item label="阈值设置" prop="warnRuleThresholdList">
          <el-card shadow="never" class="threshold-card">
            <el-row v-for="(item, index) in form.warnRuleThresholdList" :key="index" :gutter="10" class="threshold-item">
              <el-col :span="8">
                <el-form-item
                  :prop="`warnRuleThresholdList.${index}.parameterName`"
                  :rules="{ required: true, message: '请选择参数', trigger: 'change' }"
                >
                  <el-select v-model="item.parameterName" placeholder="选择参数" style="width: 100%">
                    <el-option v-for="param in parameterOptions" :key="param.value" :label="param.label" :value="param.value" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item :prop="`warnRuleThresholdList.${index}.minValue`">
                  <el-input v-model="item.minValue" placeholder="最小阈值" clearable>
                    <template #prepend>最小值</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item :prop="`warnRuleThresholdList.${index}.maxValue`">
                  <el-input v-model="item.maxValue" placeholder="最大阈值" clearable>
                    <template #prepend>最大值</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="4" class="threshold-actions">
                <el-button type="danger" icon="Delete" circle @click="removeThreshold(index)" />
              </el-col>
            </el-row>
            <div class="threshold-help">
              <p>提示：</p>
              <ul>
                <li>设置最小值表示参数应大于等于此值</li>
                <li>设置最大值表示参数应小于等于此值</li>
                <li>同时设置最小值和最大值表示参数应在此范围内</li>
                <li>可以只设置最小值或只设置最大值</li>
              </ul>
            </div>
            <el-button type="primary" plain icon="Plus" @click="addThreshold">添加阈值条件</el-button>
          </el-card>
        </el-form-item>

        <el-form-item label="规则描述" prop="remark">
          <el-input v-model="form.remark" type="textarea" :rows="3" placeholder="请输入规则描述" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="dialogVisible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 测试规则弹窗 -->
    <el-dialog v-model="testDialogVisible" title="测试规则" width="600px" destroy-on-close>
      <el-form :model="testForm" label-width="150px">
        <el-form-item v-for="(item, index) in currentRule.warnRuleThresholdList" :key="index" :label="getParameterLabel(item.parameterName)">
          <el-input v-model="testForm[item.parameterName]" :placeholder="`请输入${getParameterLabel(item.parameterName)}测试值`" />
        </el-form-item>
      </el-form>
      <div class="test-result" v-if="testResult !== null">
        <el-alert
          :title="testResult ? '预警规则将触发' : '预警规则不会触发'"
          :type="testResult ? 'warning' : 'info'"
          :description="testResultDescription"
          show-icon
        />
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="runTest">运行测试</el-button>
          <el-button @click="testDialogVisible = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, watch, nextTick, getCurrentInstance, type ComponentInternalInstance } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Message, ChatLineRound, Bell } from '@element-plus/icons-vue';
import { listData } from '@/api/system/dict/data';
import type { DictDataVO } from '@/api/system/dict/data/types';
import { getWarningRuleList, getWarningRuleById, addWarningRule, updateWarningRule, deleteWarningRule } from '@/api/bridge/traffic/rule';
import dayjs from 'dayjs';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

interface DictOption {
  dictValue: string;
  dictLabel: string;
  dictType?: string;
  unit?: string;
}

interface ParameterOption {
  value: string;
  label: string;
}

// 测试相关的状态
const testDialogVisible = ref(false);
const testForm = ref<Record<string, any>>({});
const testResult = ref<boolean | null>(null);
const testResultDescription = ref('');
const currentRule = ref<any>({});
const showSearch = ref(true);

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  ruleName: ''
});

// 表单参数
const form = reactive({
  ruleId: undefined,
  ruleName: '',
  warningType: '',
  triggerCondition: '',
  warningLevel: '',
  notificationMethod: [] as string[],
  status: 0,
  remark: '',
  warnRuleThresholdList: [{ parameterName: '', minValue: '', maxValue: '' }]
});

// 添加编辑模式标志
const isEditMode = ref(false);

// 字典数据
const warningTypeOptions = ref<DictOption[]>([]);
const warningLevelOptions = ref<DictOption[]>([]);
const notificationMethodOptions = ref<DictOption[]>([]);

// 获取预警类型字典
const getWarningTypeDict = async () => {
  const res = await listData({
    dictType: 'warning_type',
    pageNum: 1,
    pageSize: 100,
    dictName: '',
    dictLabel: ''
  });
  warningTypeOptions.value = res.rows;
};

// 获取预警级别字典
const getWarningLevelDict = async () => {
  const res = await listData({
    dictType: 'warn_level',
    pageNum: 1,
    pageSize: 100,
    dictName: '',
    dictLabel: ''
  });
  warningLevelOptions.value = res.rows;
};

// 获取通知方式字典
const getNotificationMethodDict = async () => {
  const res = await listData({
    dictType: 'notification_method',
    pageNum: 1,
    pageSize: 100,
    dictName: '',
    dictLabel: ''
  });
  notificationMethodOptions.value = res.rows;
};

// 获取通知方式文本
const getNotificationMethodText = (methods: string[]) => {
  return methods
    .map((method) => {
      const found = notificationMethodOptions.value.find((item) => item.dictValue === method);
      return found ? found.dictLabel : method;
    })
    .join('、');
};

// 判断是否包含特定通知方式
const hasNotificationMethod = (methods: string[], method: string) => {
  return methods.includes(method);
};

// 获取预警参数选项
const getParameterOptions = async (warningType: string): Promise<DictOption[]> => {
  // 获取通用参数
  const commonParamsRes = await listData({
    dictType: 'common_params',
    pageNum: 1,
    pageSize: 100,
    dictName: '',
    dictLabel: ''
  });
  let commonParams = commonParamsRes.rows || [];

  // 根据预警类型获取对应的参数字典类型
  const paramDictType: Record<string, string> = {
    '1': 'accident_params', // 交通拥堵
    '2': 'environmental_params', // 环境污染
    '3': 'geology_params', // 地质灾害
    '4': 'health_params', // 公共卫生
    '5': 'weather_params' // 气象灾害
  };

  // 获取特定类型的参数
  const specificType = paramDictType[warningType];
  const specificParamsRes = await listData({
    dictType: specificType,
    pageNum: 1,
    pageSize: 100,
    dictName: '',
    dictLabel: ''
  });
  let specificParams = specificParamsRes.rows || [];

  // 合并通用参数和特定参数
  return [...commonParams, ...specificParams];
};

// 状态选项
const statusOptions = [
  { value: 0, label: '启用' },
  { value: 1, label: '禁用' }
];

// 参数选项
const parameterOptions = ref<ParameterOption[]>([]);

// 获取参数选项
const loadParameterOptions = async (type: string) => {
  try {
    const options = await getParameterOptions(type);
    return options.map((option) => ({
      value: option.dictValue,
      label: `${option.dictLabel}${option.unit ? `(${option.unit})` : ''}`
    }));
  } catch (error) {
    console.error('获取参数选项失败:', error);
    return [];
  }
};

// 监听预警类型变化，获取对应的参数选项
watch(
  () => form.warningType,
  async (newType) => {
    if (newType) {
      parameterOptions.value = await loadParameterOptions(newType);
      // 只有在非编辑模式下才重置阈值设置
      if (!isEditMode.value) {
        form.warnRuleThresholdList = [{ parameterName: '', minValue: '', maxValue: '' }];
      }
    } else {
      parameterOptions.value = [];
    }
  }
);

// 获取预警级别类型
const getWarningLevelType = (level: string): 'success' | 'warning' | 'info' | 'primary' | 'danger' => {
  switch (level) {
    case '1': // I级（特别重大）
      return 'danger'; // 红色
    case '2': // II级（重大）
      return 'warning'; // 橙色
    case '3': // III级（较大）
      return 'warning'; // 黄色
    case '4': // IV级（一般）
      return 'info'; // 蓝色
    default:
      return 'info';
  }
};

// 获取预警级别名称
const getWarningLevelName = (level: string) => {
  const found = warningLevelOptions.value.find((item) => item.dictValue === level);
  return found ? found.dictLabel : '';
};

// 获取预警类型名称
const getWarningTypeName = (type: string) => {
  const found = warningTypeOptions.value.find((item) => item.dictValue === type);
  return found ? found.dictLabel : '';
};

// 获取参数标签
const getParameterLabel = (paramValue: string): string => {
  const option = parameterOptions.value.find((item) => item.value === paramValue);
  return option ? option.label : paramValue;
};

// 列表数据
const ruleList = ref<any[]>([]);
const loading = ref(false);
const total = ref(0);

// 表单校验规则
const rules = {
  ruleName: [{ required: true, message: '规则名称不能为空', trigger: 'blur' }],
  warningType: [{ required: true, message: '预警类型不能为空', trigger: 'change' }],
  triggerCondition: [{ required: true, message: '触发条件不能为空', trigger: 'blur' }],
  warningLevel: [{ required: true, message: '预警级别不能为空', trigger: 'change' }],
  notificationMethod: [
    {
      required: true,
      message: '请至少选择一种通知方式',
      trigger: 'change',
      type: 'array' as const
    }
  ],
  warnRuleThresholdList: [
    {
      required: true,
      message: '请至少设置一个阈值条件',
      trigger: 'change',
      type: 'array' as const
    },
    {
      validator: (rule: any, value: any[], callback: Function) => {
        if (!value || value.length === 0) {
          callback(new Error('请至少设置一个阈值条件'));
          return;
        }

        // 检查每个阈值设置
        for (let i = 0; i < value.length; i++) {
          const item = value[i];

          // 检查参数名称
          if (!item.parameterName) {
            callback(new Error(`第${i + 1}个阈值条件的参数名称不能为空`));
            return;
          }

          // 转换最小值和最大值为数字
          const minValue = Number(item.minValue);
          const maxValue = Number(item.maxValue);

          // 检查是否至少设置了一个阈值
          if (isNaN(minValue) && isNaN(maxValue)) {
            callback(new Error(`第${i + 1}个阈值条件至少需要设置最小值或最大值`));
            return;
          }

          // 如果两个值都设置了，检查大小关系
          if (!isNaN(minValue) && !isNaN(maxValue)) {
            if (minValue >= maxValue) {
              callback(new Error(`第${i + 1}个阈值条件的最小值必须小于最大值`));
              return;
            }
          }
        }

        callback();
      },
      trigger: 'change'
    }
  ]
};

// 对话框参数
const dialogVisible = ref(false);
const dialogTitle = ref('');
const ruleFormRef = ref<any>(null);
const queryFormRef = ref<any>(null);

// 页面初始化
onMounted(() => {
  getWarningTypeDict();
  getWarningLevelDict();
  getNotificationMethodDict();
  getList();
});

// 获取规则列表
const getList = async () => {
  loading.value = true;
  try {
    const res = await getWarningRuleList(queryParams);
    // 处理返回的数据，将通知方式字符串转换为数组，并将 id 映射为 ruleId
    ruleList.value = res.rows.map((item) => ({
      ...item,
      ruleId: item.id,
      notificationMethod: item.notificationMethod ? item.notificationMethod.split(',') : []
    }));
    total.value = res.total;
  } catch (error) {
    console.error('获取预警规则列表失败:', error);
  } finally {
    loading.value = false;
  }
};

// 格式化日期
const formatDate = (dateString: string) => {
  return dayjs(dateString).format('YYYY-MM-DD HH:mm');
};

// 搜索按钮操作
const handleQuery = () => {
  queryParams.pageNum = 1;
  getList();
};

// 重置按钮操作
const resetQuery = () => {
  queryParams.ruleName = null;
  queryFormRef.value?.resetFields();
  getList();
};

// 新增按钮操作
const handleAdd = () => {
  resetForm();
  isEditMode.value = false;
  dialogTitle.value = '新增预警规则';
  dialogVisible.value = true;
};

// 编辑按钮操作
const handleEdit = async (row: any) => {
  resetForm();
  isEditMode.value = true;
  dialogTitle.value = '编辑预警规则';

  try {
    const { data } = await getWarningRuleById(row.id);
    // 先设置预警类型，触发参数选项加载
    form.warningType = data.warningType;
    // 等待参数选项加载完成
    await nextTick();

    // 处理返回的数据，将通知方式字符串转换为数组
    const formData = {
      ...data,
      ruleId: data.id,
      notificationMethod: data.notificationMethod ? data.notificationMethod.split(',') : []
    };

    Object.assign(form, formData);
    dialogVisible.value = true;
  } catch (error) {
    console.error('获取规则详情失败:', error);
    ElMessage.error('获取规则详情失败');
  }
};

// 删除按钮操作
const handleDelete = (row: any) => {
  ElMessageBox.confirm(`确定要删除预警规则"${row.ruleName}"吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      await deleteWarningRule(row.id);
      ElMessage.success('删除成功');
      getList();
    })
    .catch(() => {});
};

// 状态变更操作
const handleStatusChange = async (row: any) => {
  // 处理提交的数据，将通知方式数组转换为逗号分隔的字符串
  const submitData = {
    ...row,
    notificationMethod: Array.isArray(row.notificationMethod) ? row.notificationMethod.join(',') : row.notificationMethod
  };
  await updateWarningRule(submitData);
  ElMessage.success(`规则已${row.status === 0 ? '启用' : '禁用'}`);
};

// 测试按钮操作
const handleTest = (row: any) => {
  currentRule.value = row;
  testForm.value = {};
  testResult.value = null;
  testResultDescription.value = '';

  // 为每个阈值参数创建输入字段
  row.warnRuleThresholdList.forEach((item: any) => {
    testForm.value[item.parameterName] = '';
  });

  testDialogVisible.value = true;
};

// 运行测试
const runTest = () => {
  // 判断测试结果
  const results = currentRule.value.warnRuleThresholdList.map((setting: any) => {
    const testValue = Number(testForm.value[setting.parameterName]);
    const minValue = Number(setting.minValue);
    const maxValue = Number(setting.maxValue);
    let result = true;

    if (!isNaN(minValue) && testValue < minValue) {
      result = false;
    }

    if (!isNaN(maxValue) && testValue > maxValue) {
      result = false;
    }

    return {
      parameterName: setting.parameterName,
      parameterLabel: getParameterLabel(setting.parameterName),
      result,
      testValue,
      minValue,
      maxValue
    };
  });

  // 所有条件都满足才触发预警
  testResult.value = results.every((r) => r.result);

  // 生成结果描述
  testResultDescription.value = results
    .map((r) => {
      let conditionText = '';
      if (!isNaN(r.minValue) && !isNaN(r.maxValue)) {
        conditionText = `${r.minValue} <= ${r.testValue} <= ${r.maxValue}`;
      } else if (!isNaN(r.minValue)) {
        conditionText = `${r.testValue} >= ${r.minValue}`;
      } else if (!isNaN(r.maxValue)) {
        conditionText = `${r.testValue} <= ${r.maxValue}`;
      }

      return `${r.parameterLabel} ${conditionText}：${r.result ? '满足' : '不满足'}`;
    })
    .join('\n');
};

// 重置表单
const resetForm = () => {
  isEditMode.value = false;
  form.ruleId = undefined;
  form.ruleName = '';
  form.warningType = '';
  form.triggerCondition = '';
  form.warningLevel = '';
  form.notificationMethod = [];
  form.status = 0; // 默认启用
  form.remark = '';
  form.warnRuleThresholdList = [{ parameterName: '', minValue: '', maxValue: '' }];
  ruleFormRef.value?.resetFields();
};

// 添加阈值条件
const addThreshold = () => {
  form.warnRuleThresholdList.push({ parameterName: '', minValue: '', maxValue: '' });
};

// 移除阈值条件
const removeThreshold = (index: number) => {
  form.warnRuleThresholdList.splice(index, 1);
  if (form.warnRuleThresholdList.length === 0) {
    addThreshold();
  }
};

// 提交表单
const submitForm = () => {
  ruleFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      // 处理提交的数据，将通知方式数组转换为逗号分隔的字符串
      const submitData = {
        ...form,
        id: form.ruleId,
        notificationMethod: form.notificationMethod.join(',')
      };

      if (form.ruleId) {
        await updateWarningRule(submitData);
        ElMessage.success('修改成功');
      } else {
        await addWarningRule(submitData);
        ElMessage.success('新增成功');
      }
      dialogVisible.value = false;
      getList();
    }
  });
};

// 分页处理
const handlePageChange = (val: number) => {
  queryParams.pageNum = val;
  getList();
};

// 每页条数变更
const handleSizeChange = (val: number) => {
  queryParams.pageSize = val;
  getList();
};
</script>

<style scoped lang="scss">
.rule-container {
  padding: 20px;
}

.header-section {
  text-align: center;
  margin-bottom: 30px;
}

.title-font {
  font-size: 2.2rem;
  color: var(--el-text-color-primary);
  font-weight: 600;
  letter-spacing: 2px;
  margin-bottom: 1rem;
}

.title-divider {
  width: 80px;
  height: 3px;
  background: #409eff;
  margin: 0 auto;
  border-radius: 2px;
}

.action-area {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.notification-icons {
  display: flex;
  justify-content: center;
  gap: 5px;
}

.notify-users {
  display: flex;
  align-items: center;
  justify-content: center;

  .more-users {
    font-size: 12px;
    background-color: #f2f6fc;
    color: #909399;
    border-radius: 50%;
    width: 25px;
    height: 25px;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-left: -8px;
  }
}

.threshold-card {
  width: 100%;
  border: 1px solid var(--el-border-color-light);
  margin-top: 10px;
}

.threshold-item {
  margin-bottom: 10px;
  display: flex;
  align-items: center;
}

.threshold-actions {
  display: flex;
  justify-content: center;
  align-items: center;
}

.threshold-help {
  background-color: #f2f6fc;
  padding: 10px 15px;
  border-radius: 4px;
  margin: 10px 0 15px;

  p {
    font-weight: bold;
    margin-bottom: 5px;
    margin-top: 0;
  }

  ul {
    margin: 0;
    padding-left: 20px;

    li {
      margin-bottom: 3px;
      font-size: 12px;
      color: #606266;
    }
  }
}

.test-result {
  margin-top: 20px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .action-area {
    flex-direction: column;
    align-items: stretch;
  }

  .action-buttons {
    margin-left: 0;
    margin-top: 10px;
    display: flex;
    justify-content: flex-end;
  }
}
</style>
